#!/usr/bin/python
# -*- coding: utf-8 -*-
import simplejson as json
from grab import Grab
from jbotclass import jsend
url = "http://search.twitter.com/search.json?q=tmradio&lang=ru"
g = Grab()
g.setup(timeout = 60, connect_timeout = 50)
g.go(url)
response = str(g.response.body)
jsonData = json.loads(response)

last_max_id = None
try:
	f = open('/home/ekis/tornado/twmaxid.txt', 'r')
	last_max_id = int(f.read())
	f.close()
	print "last_max_id was:", last_max_id
except: pass
max_id = jsonData['max_id']
print "twitter returned max_id", max_id
results = jsonData['results']
alertJIDs = 'hakimovis@ya.ru;tramp.uln@gmail.com'
for row in results:
	id = row['id']
	if last_max_id and id>last_max_id:
		from_user = row.get('from_user', u'Неизвестно')
		text = row.get('text', u'')
		created_at = row.get('created_at', '')
		lText = text.lower()
		found = False
		if u'эфир' in lText and not '--' in lText:
			found = True
			if from_user in ('dugwin', 'umonkey'):
				found = True
			else:
				for word in [u'запис', u'получил', u' был']:
					if word in lText: found = False
		if found:
			alertString = u"%s %s: %s"%(created_at, from_user, text)
			#print alertString
			jsend(alertJIDs, alertString)
		f = open("/home/ekis/tornado/messagefile.txt",'a')
		toChat = u"twitter.com/%s: %s\n"%(from_user, text)
		f.write(toChat.encode('utf-8'))
		f.close()
if not last_max_id or last_max_id<max_id:
    f = open('/home/ekis/tornado/twmaxid.txt','w')
    f.write(str(max_id))
    f.close()
